﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using smartphone.App_Code;

namespace smartphone.UserControls
{
    public partial class AdminAttributeType : System.Web.UI.UserControl
    {
        private Catalog catalog = new Catalog();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["AttrID"] != null)
            {
                this.Visible = false;
            }
            else
            {
                if (!IsPostBack)
                {
                    this.Visible = true;
                    BindGrid();
                }
            }
        }

        private void BindGrid()
        {
            GridViewAttrType.DataSource = catalog.GetAttrType();
            GridViewAttrType.DataBind();
        }

        protected void GridViewAttrType_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string id = GridViewAttrType.DataKeys[e.RowIndex].Value.ToString();
            bool success = catalog.DeleteAttr(Int32.Parse(id));
            
            GridViewAttrType.EditIndex = -1;
            LabelInform.Text = success ? "Xóa thành công" : "Xóa thất bại";
            BindGrid();
        }

        protected void GridViewAttrType_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string id = GridViewAttrType.DataKeys[e.RowIndex].Value.ToString();
            string name = ((TextBox)GridViewAttrType.Rows[e.RowIndex].Cells[0].Controls[0]).Text;

            bool success = catalog.UpdateAttrType(Int32.Parse(id), name);
            GridViewAttrType.EditIndex = -1;
            LabelInform.Text = success ? "Cập nhật thành công" : "Cập nhật thất bại";
            BindGrid();
        }

        protected void GridViewAttrType_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridViewAttrType.EditIndex = e.NewEditIndex;

            LabelInform.Text = "Sửa dòng số: " + e.NewEditIndex.ToString();
            BindGrid();
        }

        protected void GridViewAttrType_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridViewAttrType.EditIndex = -1;
            LabelInform.Text = "Hủy sửa";
            BindGrid();
        }

        protected void BtCreateAttrType_Click(object sender, EventArgs e)
        {
            string name = TxtAttrTypeName.Text;
            bool success = catalog.CreateAttr(name);

            LabelInform2.Text = success ? "Thêm thành công" : "Thêm thất bại";
            BindGrid();
        }
    }
}